package com.itheima.stock.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.itheima.stock.common.domian.RoleAddDomain;
import com.itheima.stock.common.domian.UserDomin;
import com.itheima.stock.common.domian.UserPageDomain;
import com.itheima.stock.mapper.SysPermissionMapper;
import com.itheima.stock.mapper.SysRoleMapper;
import com.itheima.stock.mapper.SysRolePermissionMapper;
import com.itheima.stock.pojo.SysRole;
import com.itheima.stock.service.RolesService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.code.ResponseCode;
import com.itheima.stock.vo.req.UserMenus;
import com.itheima.stock.vo.resp.PageResult;
import com.itheima.stock.vo.result.R;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.User;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.index.PathBasedRedisIndexDefinition;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @author: siwukun
 * @date: 2022/06/10
 * @description:
 */
@Service
public class RolesServiceImpl implements RolesService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Autowired
    private IdWorker idWorker;
    /**
     * 角色分页查询
     *
     * @param pageNum  当前页码
     * @param pageSize 条数
     * @return
     */
    @Override
    public R<PageResult<PageInfo>> getUserByPageInfo(UserPageDomain userPageDomain) {
        if (userPageDomain == null) {
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //单表可以直接使用PageHelper，多表另做处理
        PageHelper.offsetPage(userPageDomain.getPageNum(), userPageDomain.getPageSize());
        List<SysRole> roles = sysRoleMapper.getUserByPageInfo();
        //把查询的数据进行封装
        PageInfo<SysRole> pageInfo = new PageInfo<>(roles);
        //将pageInfo进行二次封装响应给前端
        PageResult pageResult = new PageResult(pageInfo);
        return R.ok(pageResult);
    }

    @Override
    public R<List<UserMenus>> getPermissionEcho() {
        //查询所有的权限
        List<UserMenus> pers = sysPermissionMapper.getPermissionEcho();
        if (pers == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA.getMessage());

        }
        //根据1级的id找到相对应的二级目录pid
        List<UserMenus> list = PermissionTree(pers);
       return R.ok(list);
    }

    private List<UserMenus> PermissionTree(List<UserMenus> pers) {
        List<UserMenus> list = new ArrayList<>();
        for (UserMenus per : pers) {
            //根据1级的id找到相对应的二级目录pid
            list = sysPermissionMapper.getTwoPermissionEcho(per.getId());
            if (list != null) {
                per.setChildren(list);
                for (UserMenus menus : list) {
                    //根据1级的id找到相对应的二级目录pid
                    list = sysPermissionMapper.getThreePermissionEcho(menus.getId());
                    if (list != null) {
                        menus.setChildren(list);
                    }
                }
            }
        }
        return pers;
    }


    /**
     * 添加角色信息
     * @param roleAddDomain
     * @return
     */
    @Transactional
    @Override
    public R<String> addRoles(RoleAddDomain roleAddDomain) {
        if (roleAddDomain==null){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        int num = 0;
        roleAddDomain.setCreateTime(new Date());
        roleAddDomain.setUpdateTime(new Date());
        roleAddDomain.setDeleted(1);
        roleAddDomain.setId(idWorker.nextId());
        boolean flag = sysRoleMapper.addRoles(roleAddDomain);
        if (flag){
            for (String permissionsId : roleAddDomain.getPermissionsIds()) {
                long id = idWorker.nextId();
                num = sysRoleMapper.insertRolesAndPermission(id,roleAddDomain.getId(),permissionsId,new Date());
            }
            if (num >0){
                return R.ok(ResponseCode.SUCCESS.getMessage());
            }
        }
        return R.error(ResponseCode.ERROR.getMessage());
    }

    @Override
    public R<List<String>> getAllPid(String roleId) {

        if (Strings.isNullOrEmpty(roleId)){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        List<String> pids = sysRolePermissionMapper.getAllPidByRoleId(roleId);
        if (pids==null){
            return R.error(ResponseCode.ERROR.getMessage());
        }
        return R.ok(pids);
    }

    /**
     * 更新角色信息，包含角色关联的权限信息
     * @param roleAddDomain
     * @return
     */
    @Transactional
    @Override
    public R<String> updateRoleByRoleId(RoleAddDomain roleAddDomain) {

        if (roleAddDomain==null){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        roleAddDomain.setUpdateTime(new Date());
       int num =  sysRoleMapper.updateByPrimaryKey(roleAddDomain);
        if (num>0){
         //先删除先用的权限，之后插入新的权限
            boolean flag = sysRolePermissionMapper.deleteByRid(roleAddDomain.getId());
            if (flag){
                for (String permissionsId : roleAddDomain.getPermissionsIds()) {
                   flag =  sysRolePermissionMapper.insertPersissonByRid(idWorker.nextId(),roleAddDomain.getId(),permissionsId,new Date());
                }
                if (flag){
                    return R.ok(ResponseCode.SUCCESS.getMessage());
                }
            }
        }
        return R.error(ResponseCode.ERROR.getMessage());
    }
    /**
     * 根据角色id删除角色信息
     * @param roleId 角色id
     * @return
     */
    @Override
    public R<String> deleteFormById(String roleId) {

        if (Strings.isNullOrEmpty(roleId)){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //因为角色id都不存在了权限表也要删除对应的权限信息没有主外键关系，直接删主表信息再删从表
        int i = sysRoleMapper.deleteByPrimaryKey(Long.parseLong(roleId));
        if (i>0){
            sysRolePermissionMapper.deleteByRid(Long.parseLong(roleId));
         return R.ok(ResponseCode.SUCCESS.getMessage());
        }
        return R.error(ResponseCode.ERROR.getMessage());
    }

    @Override
    public R<String> updateRoleStatus(String roleId, Integer status) {
        if (Strings.isNullOrEmpty(roleId) || status ==null ){
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        boolean flag = sysRoleMapper.updateRoleStatus(roleId,status);
        if (!flag){
            return R.error(ResponseCode.ERROR.getMessage());
        }
      return   R.ok(ResponseCode.SUCCESS.getMessage());
    }
}
